package com.lnj.messages.configs;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import dev.langchain4j.store.embedding.elasticsearch.ElasticsearchEmbeddingStore;
import jakarta.annotation.PostConstruct;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ElasticClientConfig {

    @Bean
    public RestClient restClient() {
        return RestClient.builder(
                new HttpHost("localhost", 9269, "http") // Changed to default port 9200
        ).build();
    }

    @Bean
    public ElasticsearchTransport elasticsearchTransport(RestClient restClient) {
        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }

    @Bean
    public ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) {
        ElasticsearchClient client = new ElasticsearchClient(transport);
        initializeIndex(client); // Initialize index when creating the client
        return client;
    }

    private void initializeIndex(ElasticsearchClient client) {
        try {
            if (!client.indices().exists(e -> e.index("product_vectors")).value()) {
                client.indices().create(c -> c
                        .index("product_vectors")
                        .mappings(m -> m
                                .properties("productId", p -> p.keyword(k -> k))
                                .properties("productVector", p -> p
                                        .denseVector(dv -> dv
                                                .dims(1024)
                                                .index(true)
                                                .similarity("cosine")
                                        )
                                )
                        )
                );
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to initialize Elasticsearch index", e);
        }
    }
}
